package com.hb.unic.core.context.support;

import java.util.HashSet;
import java.util.Properties;
import java.util.Set;

import com.hb.unic.core.context.Application;
import com.hb.unic.core.context.UnicApplicationProperties;
import org.springframework.beans.factory.config.YamlPropertiesFactoryBean;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.env.EnvironmentPostProcessor;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.env.MutablePropertySources;
import org.springframework.core.env.PropertiesPropertySource;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.PropertiesLoaderUtils;

import lombok.SneakyThrows;

/**
 * environment后置处理器，此类是无法打印日志的
 *
 * @since v1.0，2023/8/30 20:18，create by Mr.Huang.
 */
public class UnicEnvironmentPostProcessor implements EnvironmentPostProcessor {

    /**
     * 加载的配置文件名集合
     */
    public static final Set<String> LOAD_PROPERTIES_FILENAMES = new HashSet<>();

    @SneakyThrows
    @Override
    public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) {
        MutablePropertySources propertySources = environment.getPropertySources();
        // 加载properties文件
        PathMatchingResourcePatternResolver resolver1 = new PathMatchingResourcePatternResolver();
        Resource[] resources1 = resolver1.getResources("classpath*:config/service-*-config.properties");
        for (Resource resource : resources1) {
            Properties properties = PropertiesLoaderUtils.loadProperties(resource);
            String filename = resource.getFilename();
            propertySources.addLast(new PropertiesPropertySource(filename, properties));
            LOAD_PROPERTIES_FILENAMES.add(filename);
        }
        // 加载yaml文件
        YamlPropertiesFactoryBean yamlPropertiesFactoryBean = new YamlPropertiesFactoryBean();
        PathMatchingResourcePatternResolver resolver2 = new PathMatchingResourcePatternResolver();
        Resource[] resources2 = resolver2.getResources("classpath*:config/service-*-config.yml");
        for (Resource resource : resources2) {
            yamlPropertiesFactoryBean.setResources(resource);
            Properties properties = yamlPropertiesFactoryBean.getObject();
            String filename = resource.getFilename();
            propertySources.addLast(new PropertiesPropertySource(filename, properties));
            LOAD_PROPERTIES_FILENAMES.add(filename);
        }
        // 设置应用上下文
        Application.setProperties(new UnicApplicationProperties(environment));
    }

}
